import { HsAdminDelete, HsAdminInput, HsAdminPage, HsAdminSelect, HsAdminSortTable, HsAdminSpin } from '@hs-admin/base-components'
import { Button, Col, Divider, Flex, Modal, Radio, Row, Switch, Tooltip } from 'antd'
import { FC, MutableRefObject, SetStateAction, useEffect, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import Filtrate from './Filtrate'
import { reqDataItemColumns, reqDataItemInfo, sortDataItemColumn, updateCoreFieldData } from '@hs-admin/api'
import { HsAdminDataItemExample } from '@hs-admin/components'
import { useImmer } from 'use-immer'
import { CheckCircleOutlined, CloseCircleOutlined, EditOutlined, QuestionCircleOutlined } from '@ant-design/icons'
import { GlobalPublishDataItem } from '@/components/GlobalScrollSelect'
import {
  addDataItemGroup,
  addRelationDataItem,
  deleteDataItemGroup,
  deleteRelationDataItem,
  editRelationDataItem,
  getDataItemGroupList,
  getRelationDataItemList,
  updateDataItemGroup
} from '@/api/setting/item'
import { message, usePage } from '@hs-admin/utils'
import './style.less'
import { ServerCoreField } from '@hs-server/components'
import Sort from './Sort'

const Setting: FC = () => {
  const [searchParams] = useSearchParams()
  const id: string = searchParams?.get('id') || ''
  const [loading, setloading] = useState(true)
  const [itemInfor, setitemInfor] = useState<any>({})
  const [exampleId, setexampleId] = useState('')
  const [isExampleModalOpen, setIsExampleModalOpen] = useState(false)
  const [exampleName, setexampleName] = useState('')
  const [relationList, setrelationList] = useImmer<any[]>([{}])
  const selectedGroupItem = useRef<any>({})
  const { DetailGroup, groupList, showGroupModal } = useDetailGroup(selectedGroupItem, () => {
    selectedGroupItem.current = {}
    callFieldList()
  })
  const selectGroupList = [
    ...groupList.map((item) => ({
      ...item,
      label: item.name,
      value: item.id
    })),
    { label: '+添加分组', value: '+添加分组' }
  ]
  const columns = [
    {
      title: '字段名',
      dataIndex: 'name'
    },
    {
      title: '中文名',
      dataIndex: 'comment'
    },
    {
      title: '字段类型',
      dataIndex: 'datatype'
    },
    {
      title: '显示名称',
      dataIndex: 'display_name',
      render: (text: string, record: { comment: string; display_name: string; id: string }) => (
        <HsAdminInput
          defaultValue={text}
          placeholder="请输入显示名称"
          onPressEnter={(e: { target: { value: any } }) => {
            record.display_name = e.target.value || null
            updateCoreFieldData({ data_product_item_id: searchParams.get('id'), column_id: record.id, ...record }).then(() => {
              message.success('修改显示名称成功')
              callFieldList()
            })
          }}
          onBlur={(e: { target: { value: any } }) => {
            record.display_name = e.target.value || null
            updateCoreFieldData({ data_product_item_id: searchParams.get('id'), column_id: record.id, ...record }).then(() => {
              message.success('修改显示名称成功')
              callFieldList()
            })
          }}
          className="w-80"
        />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>可搜索</p>
          <Tooltip title="在数据项查询中，该字段是否作为搜索功能中的搜索范围">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'searchable',
      render: (_: any, record: any, index: number) => (
        <Switch checked={!!record.searchable} onChange={(checked) => switchChange('searchable', checked, index)} />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>可查询</p>
          <Tooltip title="在数据项查询中，该字段是否可呈现在查询结果列表中展示">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'queryable',
      render: (_: any, record: any, index: number) => (
        <Switch checked={!!record.queryable} onChange={(checked) => switchChange('queryable', checked, index)} />
      )
    },
    {
      title: () => (
        <Flex gap={'small'}>
          <p>业务唯一</p>
          <Tooltip title="具有唯一性，可以作为数据的标识，如ID、企业名称等">
            <QuestionCircleOutlined />
          </Tooltip>
        </Flex>
      ),
      dataIndex: 'unique',
      render: (_: any, record: any, index: number) => (
        <Switch checked={record.unique} onChange={(checked) => switchChange('unique', checked, index)} />
      )
    },
    {
      title: '展示配置',
      dataIndex: 'display_type',
      render: (text: string, record: { name: string; display_type: any; id: any }) => {
        let options = [
          { label: '不展示', value: 'not_display' },
          { label: '火石产业', value: 'hs_ind_list' },
          { label: '国民经济分类', value: 'nea_ind_list' },
          { label: '战新产业', value: 'strategic_ind_list' },
          { label: '所属载体信息', value: 'carrier_list' },
          { label: '资质信息', value: 'qualified_list' },
          { label: '机构信息', value: 'org_info_list' },
          { label: '直接展示', value: 'direct' },
          { label: '"是否"展示', value: 'true_or_false' }
        ]
        if (['hs_ind_list', 'nea_ind_list', 'strategic_ind_list', 'carrier_list', 'qualified_list', 'org_info_list'].includes(record.name)) {
          options = options.map((item) => ({ ...item, disabled: !['not_display', 'direct', record.name].includes(item.value) }))
        }
        return (
          <Flex align="center" gap={'small'}>
            <HsAdminSelect
              value={text || 'direct'}
              options={options}
              className="min-w-20 w-full"
              onChange={(value: any) => {
                record.display_type = value || null
                updateCoreFieldData({ data_product_item_id: searchParams.get('id'), column_id: record.id, ...record }).then(() => {
                  message.success('选择展示配置成功')
                  callFieldList()
                })
              }}
              placeholder="请选择展示配置"
            />
          </Flex>
        )
      }
    },
    {
      title: '详情分组',
      dataIndex: 'column_group',
      render: (column_group_obj: any, record: { column_group: any; id: string }) => (
        <Flex align="center" gap={'middle'}>
          <HsAdminSelect
            value={column_group_obj?.id}
            className="min-w-20 w-full"
            options={selectGroupList}
            onChange={(value: any, option: any) => {
              setData([...data])
              if (Object.is(value, '+添加分组')) {
                selectedGroupItem.current = record
                showGroupModal()
              } else {
                record.column_group = option || {}
                updateCoreFieldData({ data_product_item_id: searchParams.get('id'), column_id: record.id, ...record }).then(() => {
                  message.success('选择详情分组成功')
                  callFieldList()
                })
              }
            }}
            placeholder="请选择详情分组"
          />
        </Flex>
      )
    }
  ]
  const [data, setData] = useImmer<any[]>([])
  const [fieldKeywords, setfieldKeywords] = useState(null)
  const [fieldPagination, setfieldPagination] = useState({
    page: 1,
    page_size: 199
  })

  const callList = () => {
    setloading(true)
    return getRelationDataItemList({ release_item_id: id, page: pagination.current, page_size: pagination.pageSize })
      .then((res) => {
        const list = res.items.map((item: any) => ({
          ...item,
          right_item_id: item.right_item.id,
          dataItemOptions: [{ label: item.right_item.data_item_product?.name, value: item.right_item.id }]
        }))
        setrelationList(list)
        setTotal(res.total)
        return res
      })
      .finally(() => {
        setloading(false)
      })
  }
  const { pagination, setTotal }: { pagination: UsePageProps; setTotal: (total: number) => number } = usePage(callList)

  const dataItemChange = async (index: number, value: string, option: { label: SetStateAction<string> }) => {
    const hasItem = relationList.find((item) => item.right_item_id === value)
    if (hasItem) {
      message.warning('关联数据库不可重复')
      return
    }
    setrelationList((prev) => {
      prev[index].right_item_id = value
      prev[index].right_field = null
    })
    setexampleName(option.label)
  }
  const fieldChange = (index: number, value: string) => {
    const item = relationList[index]
    if (item.id) {
      return editRelationDataItem({
        release_item_id: id,
        ...item,
        right_field: value
      })
        .then(() => {
          message.success('保存成功')
          return callList()
        })
        .catch((error) => {
          setloading(false)
          return Promise.reject(error)
        })
    } else {
      return addRelationDataItem({
        release_item_id: id,
        left_field: 'id',
        right_item_id: item.right_item_id,
        right_field: value
      })
        .then(() => {
          message.success('保存成功')
          return callList()
        })
        .catch((error) => {
          setloading(false)
          return Promise.reject(error)
        })
    }
  }
  const updateField = (key: number) => {
    const item = relationList[key]
    if (!item.right_item_id) {
      message.warning('请选择关联数据库')
      return
    }
    item.coreFieldRef?.showModal(item.right_item_id, item.right_field)
  }
  const callFieldList = async () => {
    setloading(true)
    const params = {
      id,
      ...fieldPagination,
      keywords: fieldKeywords
    }
    const res = await reqDataItemColumns(params)
    if (res.length) {
      res.forEach((item: { display_name: any; comment: any }) => {
        item.display_name ||= item.comment
      })
      setData(res)
    }
    setloading(false)
  }
  const onDragEnd = (list: any[]) => {
    list.forEach((item, index) => {
      item.position = ++index
    })
    sortDataItemColumn({
      id,
      items: list
    }).then(() => {
      callFieldList()
    })
  }
  const switchChange = (key: string, checked: boolean, index: number) => {
    const item = data[index]
    if (key === 'searchable') {
      const hasActive = data.filter((item: { searchable: number }) => item.searchable === 1)
      if (checked) {
        if (hasActive.length >= 5) {
          message.warning('可搜索最多选择5个')
          return
        }
      } else {
        if (hasActive.length === 1) {
          message.warning('可搜索至少选择1个')
          return
        }
      }
    }
    if (key === 'queryable') {
      const hasActive = data.filter((item: { queryable: number }) => item.queryable === 1)
      if (!checked) {
        if (hasActive.length === 1) {
          message.warning('可查询至少选择1个')
          return
        }
      }
    }
    if (key === 'unique') {
      item[key] = checked
      item.available = checked ? 1 : item.available
    } else {
      item[key] = checked ? 1 : 0
    }
    if (key === 'searchable' && checked) {
      item.queryable = item.searchable
      item.available = item.searchable
    }
    if (key === 'queryable' && checked) {
      item.available = item.queryable
    }
    updateCoreFieldData({
      data_product_item_id: id,
      column_id: item.id,
      ...item
    })
      .then(() => {
        message.success('保存成功')
        callList()
      })
      .catch((error) => {
        callList()
        return Promise.reject(error)
      })
  }

  useEffect(() => {
    // 获取详情
    const getInfor = async () => {
      setloading(true)
      const data = await reqDataItemInfo({ id })
      setitemInfor(data)
      setloading(false)
    }
    getInfor()
  }, [id])
  useEffect(() => {
    callFieldList()
  }, [fieldPagination])

  return (
    <div className="data-item-edit-page-wrapper">
      {loading && <HsAdminSpin />}
      <h1>{itemInfor.name}</h1>
      <h3>
        <b>数据库描述：</b>
        {itemInfor.description}
      </h3>
      <Row>
        <Col span={6}>
          <h3>
            <b>所属主题：</b>
            {itemInfor.data_topics?.map((item: { name: any }) => item.name).join('，')}
          </h3>
        </Col>
        <Col span={6}>
          <h3>
            <b>数据评分：</b>
            {itemInfor.score}
          </h3>
        </Col>
        <Col span={6}>
          <h3>
            <b>更新周期：</b>
            {itemInfor.update_frequency}
          </h3>
        </Col>
        <Col span={6}>
          <h3>
            <b>数据量：</b>
            {itemInfor.data_count}条
          </h3>
        </Col>
      </Row>
      <Row>
        <Col span={6}>
          <h3>
            <b>数据价格：</b>
            {itemInfor.price}元/条
          </h3>
        </Col>
        <Col span={6}>
          <h3>
            <b>数据特征：</b>
            {itemInfor.data_characteristics?.map((item: any) => item).join('，')}
          </h3>
        </Col>
      </Row>
      <br />
      <HsAdminInput
        className="w-90 mb-4"
        Search
        placeholder="请输入关键词"
        value={fieldKeywords}
        onChange={(e: { target: { value: SetStateAction<null> } }) => setfieldKeywords(e.target.value)}
        onPressEnter={(e: { target: { value: SetStateAction<null> } }) => {
          setfieldKeywords(e.target.value)
          setfieldPagination({
            page: 1,
            page_size: 199
          })
        }}
        onSearch={(value: SetStateAction<null>) => {
          setfieldKeywords(value)
          setfieldPagination({
            page: 1,
            page_size: 199
          })
        }}
      />
      <HsAdminSortTable id="J-data-item-edit-field-sort" columns={columns} dataSource={data} rowKey="id" onUpdateDragEnd={onDragEnd} />
      <br />
      <br />
      <Flex gap={'small'} align="center">
        <h2>筛选配置:</h2>
        <Button
          type="link"
          onClick={() => {
            setexampleId(id)
            setexampleName(itemInfor.name)
            setIsExampleModalOpen(true)
          }}>
          查看样例数据
        </Button>
      </Flex>
      <Filtrate />
      <Modal
        title={`${exampleName}样例数据`}
        open={isExampleModalOpen}
        footer={null}
        onCancel={() => {
          setexampleId('')
          setexampleName('')
          setIsExampleModalOpen(false)
        }}
        width={800}>
        <HsAdminDataItemExample dataItemId={exampleId} />
      </Modal>
      <Divider />
      <h2>关联数据库配置:</h2>
      <Row gutter={16} className="mt-2">
        <Col span={4}>
          <Button
            className="w-full mt-7"
            type="primary"
            onClick={() => {
              setrelationList((prev) => {
                prev.push({
                  right_item_id: null,
                  right_field: ''
                })
              })
            }}>
            +添加关联
          </Button>
        </Col>
        <Col span={20}>
          <Row gutter={16}>
            <Col span={12}>
              <Flex>选择关联数据库</Flex>
            </Col>
            <Col span={8}>
              <Flex align="center" gap={'small'}>
                选择关联字段
                <Tooltip title="选择能与当前数据库的主键字段一致的字段，用作两个数据库的关联查询。">
                  <QuestionCircleOutlined />
                </Tooltip>
              </Flex>
            </Col>
          </Row>
          {relationList.map((item, index) => (
            <Row key={index} gutter={16} className="mt-2">
              <Col span={12}>
                <Flex gap={'small'} align="center">
                  <GlobalPublishDataItem
                    value={item.right_item_id}
                    placeholder="选择关联数据库"
                    options={item.dataItemOptions}
                    onChange={(value: string, option: { label: SetStateAction<string> }) => dataItemChange(index, value, option)}
                    className="w-8/10"
                    allowClear={false}
                  />
                  <Button
                    type="link"
                    onClick={() => {
                      if (!item.right_item_id) {
                        message.warning('请选择关联数据库')
                        return
                      }
                      setexampleId(item.right_item_id)
                      setIsExampleModalOpen(true)
                    }}>
                    查看样例数据
                  </Button>
                </Flex>
              </Col>
              <Col span={8}>
                <Button
                  className="w-full"
                  onClick={() => updateField(index)}
                  style={{ color: item.right_field ? 'rgba(0, 0, 0, 0.88)' : 'rgba(0, 0, 0, 0.25)' }}>
                  {item.right_field || '请选择关联字段'}
                </Button>
                <ServerCoreField
                  ref={(el) => {
                    setrelationList((prev) => {
                      if (prev.length && prev[index] && !prev[index].coreFieldRef) {
                        prev[index].coreFieldRef = el
                      }
                    })
                  }}
                  onSelectChange={(value: string) => fieldChange(index, value)}
                />
              </Col>
              <Col span={4}>
                <Flex align="center" gap={'small'} className="h-full">
                  <HsAdminDelete
                    onConfirm={() => {
                      if (item.id) {
                        deleteRelationDataItem({
                          release_item_id: id,
                          id: item.id
                        }).then(() => {
                          message.success('删除成功')
                          callList()
                        })
                      } else {
                        setrelationList((prev) => {
                          prev.splice(index, 1)
                        })
                      }
                    }}
                  />
                </Flex>
              </Col>
            </Row>
          ))}
        </Col>
      </Row>
      <Flex justify="end">
        <HsAdminPage {...pagination} />
      </Flex>
      <Sort id={id} />
      {DetailGroup}
    </div>
  )
}

const useDetailGroup = (selectedGroupItem: MutableRefObject<any>, success: { (): void; (): void }) => {
  const [searchParams] = useSearchParams()
  const [detailGroupOpen, setDetailGroupOpen] = useState(false)
  const [groupList, setgroupList] = useState<any[]>([])
  const [groupName, setgroupName] = useState('')

  const callGroupList = () => {
    getDataItemGroupList({ page_size: 99, table_id: searchParams.get('id') })
      .then((res) => {
        setgroupList(res.items ?? [])
      })
      .finally(() => {})
  }

  useEffect(() => {
    callGroupList()
  }, [])

  return {
    DetailGroup: (
      <Modal
        width={800}
        title="详情分组"
        open={detailGroupOpen}
        footer={null}
        onCancel={() => {
          setgroupName('')
          setDetailGroupOpen(false)
        }}>
        {groupList.map((item, index) => (
          <Flex align="center" gap={'small'} key={index} className="mt-4">
            {!item.edit && (
              <Radio
                checked={selectedGroupItem.current.column_group?.id === item.id}
                onChange={(e) => {
                  if (e.target.checked) {
                    updateCoreFieldData({
                      ...selectedGroupItem.current,
                      data_product_item_id: searchParams.get('id'),
                      column_id: selectedGroupItem.current.id,
                      column_group: item
                    }).then(() => {
                      message.success('选择详情分组成功')
                      success()
                      setgroupName('')
                      setDetailGroupOpen(false)
                    })
                  }
                }}>
                {item.name}
              </Radio>
            )}
            {item.edit && (
              <Flex align="center" gap={'small'}>
                <HsAdminInput
                  value={item.name}
                  allowClear
                  placeholder="输入名称"
                  onChange={(e: { target: { value: any } }) => {
                    item.name = e.target.value
                    setgroupList([...groupList])
                  }}
                />
                <CloseCircleOutlined
                  className="cursor-pointer"
                  onClick={() => {
                    item.edit = false
                    callGroupList()
                  }}
                />
                <CheckCircleOutlined
                  className="cursor-pointer mr-6"
                  onClick={() => {
                    if (!item.name) {
                      message.warning('名称不能为空')
                      return
                    }
                    item.edit = false
                    updateDataItemGroup({ pk: item.id, ...item, table_id: searchParams.get('id') }).then(() => {
                      message.success('编辑成功')
                      callGroupList()
                    })
                  }}
                />
              </Flex>
            )}
            <EditOutlined
              onClick={() => {
                item.edit = true
                setgroupList([...groupList])
              }}
            />
            {index !== groupList.length - 1 && (
              <Button
                type="link"
                onClick={() => {
                  const currentPos = item.position
                  const next = groupList[index + 1]
                  // switch
                  item.position = next.position
                  next.position = currentPos
                  // update current
                  updateDataItemGroup({ pk: item.id, ...item, table_id: searchParams.get('id') }).then(() => {
                    // update next
                    updateDataItemGroup({ pk: next.id, ...next, table_id: searchParams.get('id') }).then(() => {
                      message.success('下移成功')
                      callGroupList()
                    })
                  })
                }}>
                下移
              </Button>
            )}
            {!!index && (
              <Button
                type="link"
                onClick={() => {
                  const currentPos = item.position
                  const prev = groupList[index - 1]
                  // switch
                  item.position = prev.position
                  prev.position = currentPos
                  // update current
                  updateDataItemGroup({ pk: item.id, ...item, table_id: searchParams.get('id') }).then(() => {
                    // update prev
                    updateDataItemGroup({ pk: prev.id, ...prev, table_id: searchParams.get('id') }).then(() => {
                      message.success('上移成功')
                      callGroupList()
                    })
                  })
                }}>
                上移
              </Button>
            )}
            <Button
              type="link"
              onClick={() => {
                deleteDataItemGroup({ pk: item.id, table_id: searchParams.get('id') }).then(() => {
                  message.success('删除成功')
                  callGroupList()
                })
              }}>
              删除
            </Button>
          </Flex>
        ))}
        <Flex align="center" gap={'middle'} className="mt-4">
          <HsAdminInput
            value={groupName}
            placeholder="请输入分组名称"
            onChange={(e: { target: { value: SetStateAction<string> } }) => setgroupName(e.target.value)}
            onPressEnter={(e: { target: { value: any } }) => {
              addDataItemGroup({
                name: e.target.value,
                position: groupList.length ? groupList[0].position - 1 : 0,
                table_id: searchParams.get('id')
              }).then(() => {
                message.success('添加成功')
                setgroupName('')
                callGroupList()
              })
            }}
          />
          <Button
            type="primary"
            onClick={() => {
              if (!groupName) {
                message.warning('分组名称不能为空')
                return
              }
              addDataItemGroup({
                name: groupName,
                position: groupList.length ? groupList[0].position - 1 : 0,
                table_id: searchParams.get('id')
              }).then(() => {
                message.success('添加成功')
                setgroupName('')
                callGroupList()
              })
            }}>
            确定
          </Button>
        </Flex>
      </Modal>
    ),
    groupList,
    showGroupModal: () => {
      setDetailGroupOpen(true)
    }
  }
}

export default Setting
